package com.gamejelly.proxy.server;

import com.gamejelly.proxy.autoConfiguration.RpcService;
import com.gamejelly.proxy.pojo.RpcCall;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by haoyifen on 2017/6/1 9:00.
 */
public class ServiceProvider implements ApplicationContextAware {
    private static Logger logger = LoggerFactory.getLogger(ServiceProvider.class);

    private ApplicationContext context;

    private final Map<String, Invoker> handleMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
        Map<String, Object> rpcServiceBean = context.getBeansWithAnnotation(RpcService.class);
        if (rpcServiceBean.isEmpty()) {
            return;
        }
        for (Object bean : rpcServiceBean.values()) {
            RpcService service = AnnotationUtils.findAnnotation(bean.getClass(), RpcService.class);
            Class<?> serviceClass = bean.getClass();
            Class[] itfs = service.value();
            for (Class itf : itfs) {
                for (Method method : itf.getDeclaredMethods()) {
                    Method mtd = ClassUtils.getMethod(serviceClass, method.getName(), method.getParameterTypes());
                    Invoker invoker = new Invoker(itf.getSimpleName(),bean, mtd);
                    handleMap.put(invoker.sign, invoker);
                }
            }
        }
    }

    public Object invoke(RpcCall rpcCall) {
        String sign = rpcCall.getClassName() + "." + rpcCall.getMethodName();
        Invoker invoker = handleMap.get(sign);
        Assert.notNull(invoker, sign + " service not exist");
//        Class[] parameterClasses = invoker.getParamTypes();
        Object result = null;
        try {
            result = invoker.method.invoke(invoker.bean, rpcCall.getParameters());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }
}
